<?php
namespace app\controller;

use app\model\ViewHistory;
use think\facade\Session;
use think\facade\View;
use think\Request;

class Player
{
    public function index(Request $request)
    {
        $url = $request->param('url', 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8');
        $isPost = $request->isPost();
        
        // 如果是会员且提交了视频地址，记录观看历史
        if ($isPost && !empty($url) && Session::has('member_id')) {
            ViewHistory::create([
                'member_id' => Session::get('member_id'),
                'video_url' => $url,
                'title' => $this->getVideoTitle($url),
                'created_at' => date('Y-m-d H:i:s')
            ]);
        }
        
        // 获取会员历史记录
        $history = [];
        if (Session::has('member_id')) {
            $history = ViewHistory::where('member_id', Session::get('member_id'))
                ->order('created_at', 'desc')
                ->limit(5)
                ->select();
        }
        
        return View::fetch('player/index', [
            'url' => htmlspecialchars($url, ENT_QUOTES),
            'is_post' => $isPost,
            'history' => $history,
            'is_login' => Session::has('member_id'),
            'member_name' => Session::get('member_name', '')
        ]);
    }
    
    // 获取视频标题（简单实现）
    protected function getVideoTitle($url)
    {
        $parse = parse_url($url);
        $path = $parse['path'] ?? '';
        $parts = explode('/', $path);
        $filename = end($parts);
        return str_replace('.m3u8', '', $filename);
    }
    
    
    public function recordProgress(Request $request)
{
    if (!Session::has('member_id')) {
        return json(['code' => 403, 'msg' => '请先登录']);
    }
    
    $data = $request->post();
    $url = $data['url'] ?? '';
    $progress = $data['progress'] ?? 0;
    $duration = $data['duration'] ?? 0;
    
    if (empty($url)) {
        return json(['code' => 400, 'msg' => '参数错误']);
    }
    
    // 查找最近的历史记录
    $history = ViewHistory::where('member_id', Session::get('member_id'))
        ->where('video_url', $url)
        ->order('created_at', 'desc')
        ->find();
    
    if ($history) {
        $history->progress = $progress;
        $history->duration = $duration;
        $history->save();
    } else {
        ViewHistory::create([
            'member_id' => Session::get('member_id'),
            'video_url' => $url,
            'title' => $this->getVideoTitle($url),
            'progress' => $progress,
            'duration' => $duration,
            'created_at' => date('Y-m-d H:i:s')
        ]);
    }
    
    return json(['code' => 200, 'msg' => '记录成功']);
}
}